package no.ntnu.fp.messages.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.MessageCode;
import no.ntnu.fp.model.Appointment;
import no.ntnu.fp.model.Employee;
import no.ntnu.fp.utils.XmlParser;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class AppointmentsForEmployeeMessage implements Message {

	private final Employee employee;
	private final List<Appointment> appointments;
	
	public AppointmentsForEmployeeMessage(Employee employee,
			List<Appointment> appointments) {
		this.employee = employee;
		this.appointments = new ArrayList<Appointment>(appointments);
	}

	public AppointmentsForEmployeeMessage() {
		this(null, Collections.<Appointment>emptyList());
	}
	
	public Employee getEmployee() {
		return employee;
	}

	public List<Appointment> getAppointments() {
		return appointments;
	}

	@Override
	public MessageCode getMessageCode() {
		return MessageCode.APPOINTMENTS_FOR_EMPLOYEE_MESSAGE;
	}

	@Override
	public Message fromXmlString(String xml) {
		Document doc = XmlParser.parseXmlString(xml);
		Employee employee = new Employee((Element)doc.getElementsByTagName("employee").item(0));
		NodeList employeeNodeList = doc.getElementsByTagName("appointment");
		List<Appointment> appointments = new ArrayList<Appointment>();
		for (int i = 0; i < employeeNodeList.getLength(); i++) {
			Element appointmentElement = (Element)employeeNodeList.item(i);
			appointments.add(new Appointment(appointmentElement));
		}
		return new AppointmentsForEmployeeMessage(employee, appointments);
	}

	@Override
	public String toString() {
		Document doc = XmlParser.getThreadLocalDocumentBuilder().newDocument();
		Element messageElement = doc.createElement("message");
		messageElement.appendChild(employee.toXml(doc));
		
		Element appointmentsElement = doc.createElement("appointments");
		for (Appointment appointment: appointments) {
			appointmentsElement.appendChild(appointment.toXml(doc));
		}
		
		messageElement.appendChild(appointmentsElement);
		
		return getMessageCode() + XmlParser.convertXmlToString(messageElement);
	}

}
